<template>
	<view class="media-container">
		<jade-image-upload
		 :list="media"
		 :control="control"
		 :maxCount="maxCount"
		 :compressSize="compressSize"
		 :compressQuality="compressQuality"
		 :compressWidth='compressWidth'
		 :imageSize="imageSize"
		 :sourceType="sourceType"
		 @chooseFile="chooseFile"
		 @imgDelete="mediaDelete">
		</jade-image-upload>
		<!-- 数据变化的JSON  -->
		<view style="padding: 20rpx;box-sizing: border-box;display: flex;flex-direction: column;">
			图片上传：
			<!-- #ifdef H5 -->
			<view style="padding: 20rpx;word-break: break-all;">{{media.length ? media: '暂无数据'}}</view>
			<!-- #endif -->
			<!-- #ifndef H5  -->
			<view style="padding: 20rpx;word-break: break-all;">{{media.length ? JSON.stringify(media): '暂无数据'}}</view>
			<!-- #endif -->
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				control: true,
				maxCount: 6,
				compressSize: 0.2,
				imageSize: 2,
				compressQuality: 0.8,
				compressWidth: 375,
				sourceType: ['album'],
				
				uploadTask: null,
				media: [], //数据源
			};
		},
		methods: {
			//上传
			chooseFile(e) {
				this.uploadFileToServe(e)
			},
			//中断上传并删除
			mediaDelete(e) {
				this.uploadTask ? this.uploadTask.abort() : ''
				this.media.splice(e,1)
			},
			//上传逻辑处理
			uploadFileToServe(urlList) {
				if (!urlList || urlList.length <= 0) {
					return
				};
				//以七牛云为例,可根据实际需求灵活调整
				uni.request({
					url: 'qiniu', //后端接口，仅为示例，并非真实接口地址。
					method: 'GET',
					success: (res) => {
					let baseUrl = this.vuex_config.baseUrl;
					let adminPath = this.vuex_config.adminPath;
						urlList.forEach((item) => {
							this.uploadTask = uni.uploadFile({
								url: baseUrl +adminPath + '/product/file/upload', //七牛上传接口，仅为示例
								filePath: item.src,
								name: 'file',
								header: {
									'x-ajax':'json',
									'x-token':this.vuex_token,
									'x-remember':this.vuex_remember
								},
								success: (res) => {
									console.log(res)
									let data = JSON.parse(res.data) //七牛返回的数据
									if (!data.data.url) {
										item.status = 'error'
										item.progress = '上传失败'
									} else {
										item.status = 'success'
										item.progress = '上传成功'
										item.src = data.data.url
									}
								}
							});
							this.uploadTask.onProgressUpdate((res) => {
								item.percent = res.progress
								this.media.splice(item.index,1,item)
							})
						})
					}
				});
			},
		}
	}
</script>

<style lang="scss" scoped>
	.media-container {
		padding: 30rpx 26rpx;
		box-sizing: border-box;
	}
</style>
